from fastapi import APIRouter, Depends
from app.schemas.waveup.wp_user import WpUserOutput, WpUserCreate
from app.crud.waveup.wp_user import get_wp_user_by_uid, create_wp_user
from app.api.deps import SessionDep, CurrentUser
from app.services.wp_service import get_wp_user_info
from app.core.constants import ThirdPartner
from app.crud.uc.partner_token import get_partner_token
from fastapi.exceptions import HTTPException
from app.crud.waveup.swap_stat import get_all_swap_stat

router = APIRouter(
    prefix="/wp-user",
    tags=["Waveup用户"],
)

@router.get("/", response_model=WpUserOutput)
async def get_wp_user(
    session: SessionDep,
    current_user: CurrentUser,
):
    """查询当前登录用户的Waveup用户信息"""
    # 1. 从本地缓存查询用户信息
    wp_user = await get_wp_user_by_uid(session, current_user.uid)
    # 本地缓存有数据，直接返回
    if wp_user:
        return wp_user
    
    # 2. 查询用户本地缓存Token
    wp_token = await get_partner_token(
        session=session,
        uid=current_user.uid,
        partner=ThirdPartner.WaveUp,
    )
    if not wp_token:
        raise HTTPException(status_code=400, detail="WP Token不存在")
    
    # 3.通过waveup接口查询用户信息
    res = await get_wp_user_info(wp_token.accessToken)
    if res is None or res['rc'] != 0:
        raise HTTPException(status_code=400, detail="WP用户信息查询失败")
    
    # 4. 本地缓存waveup用户信息
    # 4.1 从响应数据中提取用户信息
    wp_user_create = WpUserCreate.model_validate(res['data'])
    wp_user_create.uid = current_user.uid
    # 4.2 检查本地是否已存在用户信息
    local_wp_user = await get_wp_user_by_uid(session, current_user.uid)
    if local_wp_user:
        return local_wp_user
    # 4.3 保存到数据库
    new_wp_user = await create_wp_user(session, wp_user_create)
    if not new_wp_user:
        raise HTTPException(status_code=400, detail="WP用户信息保存失败")
    return new_wp_user

@router.get("/swap_stat")
async def get_wp_user_swap_stat(
    session: SessionDep,
    current_user: CurrentUser,
):
    """查询当前登录用户的Waveup兑换统计"""
    # 1. 从数据库查询用户所有交易对兑换统计
    swap_stat = await get_all_swap_stat(session=session, uid=current_user.uid)
    return swap_stat

